/*
 * @Author: 胡晓星
 * @Date: 2024-09-04 17:46:25
 * @LastEditors: 491256909@qq.com
 * @LastEditTime: 2025-08-12 17:32:00
 * @FilePath: -serve\src\modules\teams\teams.service.ts
 * @Description: 
 */
// app.service.ts
import { Injectable } from '@nestjs/common';
import {
  GetTeamsDto,
  CreateTeamDto,
  UpdateTeamDto,
} from './dto';
import { Repository, Like } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Teams } from './teams.entity';
import { CustomException, ErrorCode } from '@/common/exceptions/custom.exception';

@Injectable()
export class TeamsService {
  constructor(@InjectRepository(Teams) private TeamRep: Repository<Teams>) {}

  /*************    球队列表    *************/
  async findAllTeams(query: GetTeamsDto) {
    const pageSize = query.pageSize || 10;
    const pageNo = query.pageNo || 1;
    const [pageData, total] = await this.TeamRep.findAndCount({
      where: {
        team_name: Like(`%${query.team_name || ''}%`),
        session: query.session || undefined,
      },
      //   relations: { permissions: true },
      order: {
        session: 'ASC',
      },
      take: pageSize,
      skip: (pageNo - 1) * pageSize,
    });
    return { pageData, total };
  }
  async createTeam(team: CreateTeamDto) {
    const { team_name } = team;
    const existTeam = await this.findByTeamname(team_name);
    if (existTeam) {
      throw new CustomException(ErrorCode.ERR_13001);
    }

    const newTeam = this.TeamRep.create(team);
    await this.TeamRep.save(newTeam);
    return true;
  }
  // 队伍名称查重
  async findByTeamname(team_name: string) {
    return this.TeamRep.findOne({
      where: { team_name },
      select: ['id', 'team_name'],
    });
  }
  //删除单个队伍
  async removeTeam(id: number) {
    await this.TeamRep.delete(id);
    return true;
  }
  //更新单个队伍
  async updateTeam(id: number, team: UpdateTeamDto) {
    const _team = await this.findOneTeam(id);
    team = this.TeamRep.merge(_team, team);
    await this.TeamRep.save(team);
    return true;
  }
  async findOneTeam(id: number) {
    return this.TeamRep.findOne({
      where: { id },
    });
  }
}